<template>
  <div>
    <el-card class="box-card" shadow="hover">
      <div class="searchForm">
        <el-form ref="searchForm" :inline="true" :model="searchForm" :rules="rules" size="mini">
          <el-form-item prop="dateTimeRange">
            <el-date-picker v-model="searchForm.dateTimeRange" :default-time="['00:00:00', '23:59:59']" align="right"
                            end-placeholder="结束时间"
                            start-placeholder="开始时间" type="datetimerange">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="级别" prop="level">
            <el-select v-model="searchForm.level" clearable placeholder="全部" style="width:100px">
              <el-option v-for="level in levels" :key="level" :label="level" :value="level"/>
            </el-select>
          </el-form-item>
          <el-form-item label="关键字" prop="keywords">
            <el-input v-model="searchForm.keyword" clearable placeholder="请输入关键字,支持正则" style="width:300px"
                      @keyup.enter.native="onSearch">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="logsearch-panel">
        <el-table :data="logContents" cell-class-name="tableCell" style="width: 100%">
          <el-table-column align="center" label="日期" prop="time" width="200">
            <template slot-scope="scope">
              {{ $dateFormat("yyyy-MM-dd hh:mm:ss.SSS", new Date(scope.row.time)) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="来源" prop="source" width="140">
          </el-table-column>
          <el-table-column align="center" label="级别" prop="level" width="80">
          </el-table-column>
          <el-table-column label="内容">
            <template slot-scope="scope">
              <div v-html="scope.row.content"></div>
            </template>
          </el-table-column>
          <el-table-column label="更多" width="80">
            <template slot-scope="scope">
              <el-button size="small" type="text" @click="handleClickContext(scope.row)">上下文</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-drawer :visible.sync="logDrawer" :withHeader="false" size="60%">
      <h1 style="text-align:center">日志上下文</h1>
      <div id="logDiv" class="logDiv">
        <div v-for="(content,i) in contextContents" :key="i"
             :class="(currentContent.pkgLogId==content.pkgLogId&&currentContent.pkgId==content.pkgId)?'logLine current_log':'logLine'">
          <span v-if="content.time">{{ $dateFormat("yyyy-MM-dd hh:mm:ss.SSS", new Date(content.time)) }}</span>
          <span v-if="content.level" style="padding: 0 8px">{{ content.level }}</span>
          <span v-html="content.content"/>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>

import {logContextApi, logSearchApi} from "@/api/log";

export default {
  props: {
    appName: [String],
  },
  data() {
    return {
      currentPkgLogId: null,
      logDrawer: false,
      currentContent: {},
      contextContents: [],
      logContents: [],
      searchForm: {
        dateTimeRange: [
          new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()),
          new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 23, 59, 59)
        ]
      },
      levels: ["DEBUG", "INFO", "WARN", "ERROR"],
      rules: {
        dateTimeRange: [{required: true, message: "请输入时间范围", trigger: ["blur", "change"],},],
      },
    };
  },
  methods: {
    handleClickContext(logContent) {
      this.contextContents = [];
      this.logDrawer = true;
      this.currentContent = {};
      logContextApi({
        appName: this.appName,
        pkgId: logContent.pkgId,
        pkgLogId: logContent.pkgLogId,
        time: logContent.time,
        prevLogs: 50,
        nextLogs: 50
      }).then(res => {
        this.currentContent = logContent;
        this.contextContents = res ? this.highlightContents(res, 'background:yellow;color:#303133') : []
      })
    },
    onSearch() {
      this.$refs["searchForm"].validate((valid) => {
        if (valid) {
          this.doSearch();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    doSearch() {
      if (this.appName) {
        logSearchApi({
          appName: this.appName,
          from: this.searchForm.dateTimeRange[0].getTime(),
          to: this.searchForm.dateTimeRange[1].getTime(),
          size: 50,
          keyword: this.searchForm.keyword,
          level: this.searchForm.level,
        }).then(res => this.logContents = res.logContents ? this.highlightContents(res.logContents, 'background:yellow;color:#303133') : [])
      }

    },
    highlightContents(list, style) {
      if (this.searchForm.keyword != null && this.searchForm.keyword.length > 0) {
        let re = new RegExp(this.searchForm.keyword, "ig");
        list.forEach(c => {
          c.content = c.content.replace(re, "<span style='" + style + "'>$&</span>");
        })
      }
      return list;
    }
  },
  created() {
    if (!this.appName) return;
  },
  watch: {
    appName() {
      this.logContents = [];
    },
    contextContents: function () {
      this.$nextTick(function () {
        let logDiv = document.getElementById("logDiv");
        let current = document.getElementsByClassName("current_log")[0];
        if (current) {
          logDiv.scrollTop = current.offsetTop - 400;
        }
      });
    },
  },

};
</script>
<style scoped>
.el-breadcrumb {
  line-height: 20px;
  height: 20px;
  display: inline-block;
}

.el-card {
  margin-bottom: 10px;
  background: #fdfdfd;
  color: #606266;
}

.el-card /deep/ .el-card__header {
  background: #f2f6fc;
  color: #409eff;
}

.el-badge {
  margin-right: 20px;
}

.el-table /deep/ .tableCell {
  padding: 5px;
  font-size: 13px;
  line-height: 13px;
  vertical-align: top;
}

.searchForm {
  margin-bottom: 20px;
}

.logsearch-panel {
  margin-bottom: 20px;
}

.current_log {
  background: blue;
}

.logDiv {
  overflow: scroll;
  padding: 15px;
  background: #303133;
  width: 100%;
  height: 99%;
  position: absolute;
}

.logLine {
  font-size: 10px;
  color: #f2f6fc;
  margin-bottom: 5px;
}

</style>